import {combineReducers} from 'redux-immutable';
import Immutable from 'immutable';
import * as actions from './actions';
import {
    GET_CURRENT_USER_PAGE_PERMISSIONS_BEGIN,
    GET_CURRENT_USER_PAGE_PERMISSIONS_SUCCESS,
    GET_CURRENT_USER_PAGE_PERMISSIONS_FAIL
} from 'Shared/actions/currentUserContext';
import {DEFAULT_SUBMIT_DATA} from './constants';
import {createNotificationReducer as notification} from 'Shared/utils/serverNotification';
const EMPTY_ARRAY = [];
const EMPTY_OBJECT = {};
const initData = (state, action) => {
    switch(action.type) {
        case actions.GET_INIT_BEGIN:
            return state.merge({
                isFetching: true,
                message: ''
            });

        case actions.GET_INIT_SUCCESS:
            return state.merge({
                isFetching: false,
                isDealerUser: action.data.isDealerUser,
                types: action.data.types || EMPTY_ARRAY,
                enterprise: action.data.enterprise || EMPTY_OBJECT,
                brands: action.data.brands || EMPTY_ARRAY,
                message: ''
            });

        case actions.GET_WAREHOUSE_SUCCESS:
            return state.merge({
                isFetching: false,
                warehouses: action.data || EMPTY_ARRAY,
                message: ''
            });
        case actions.GET_INIT_FAIL:
            return state.merge({
                message: action.message,
                isFetching: false
            });

        default:
            return state;
    }
};

export const permission = (state, action) => {
    switch(action.type) {
        case GET_CURRENT_USER_PAGE_PERMISSIONS_BEGIN:
            return state.merge(
                Immutable.fromJS({
                    isFetching: true,
                    message: ''
                })
            );

        case GET_CURRENT_USER_PAGE_PERMISSIONS_SUCCESS:
            return state.merge(
                Immutable.fromJS({
                    isFetching: false,
                    message: '',
                    data: action.data
                })
            );

        case GET_CURRENT_USER_PAGE_PERMISSIONS_FAIL:
            return state.merge(
                Immutable.fromJS({
                    isFetching: false,
                    message: action.message
                })
            );

        default:
            return state;
    }
};

const list = (state, action) => {
    switch(action.type) {
        case actions.GET_LIST_BEGIN:
            return state.merge({
                isFetching: true,
                message: '',
                total: 0
            });

        case actions.GET_LIST_SUCCESS:
            return state.merge({
                isFetching: false,
                total: action.data.totalElements,
                message: '',
                data: action.data.content
            });

        case actions.GET_LIST_FAIL:
            return state.merge({
                isFetching: false,
                total: 0,
                message: action.message || '',
                data: EMPTY_ARRAY
            });

        default:
            return state;
    }
};

const detail = (state, action) => {
    switch(action.type) {
        case actions.GET_DETAIL_BEGIN:
            return state.merge({
                isFetching: true,
                message: '',
                data: EMPTY_OBJECT
            });

        case actions.GET_DETAIL_SUCCESS:
            return state.merge({
                isFetching: false,
                message: '',
                data: action.data
            });

        case actions.CLEAR_DATA:
        case actions.GET_DETAIL_FAIL:
            return state.merge({
                isFetching: false,
                message: action.message,
                data: EMPTY_OBJECT
            });

        default:
            return state;
    }
};

const queryCondition = (state, action) => {
    switch(action.type) {
        case actions.SAVE_QUERY_CONDITION:
            return state.set(action.name, action.value);
        case actions.RESET_QUERY_PANEL:
            return state.merge(action.data);
        case actions.GET_INIT_SUCCESS:
            return state.merge(action.conditions);
        case actions.GET_LIST_SUCCESS:
            return state.withMutations(map =>
                map
                    .set('pageSize', action.condition.pageSize)
                    .set('sortField', action.condition.sortField)
                    .set('isDesc', action.condition.isDesc)
            );

        default:
            return state;
    }
};

const queryBySort = (state, action) => {
    switch(action.type) {
        case actions.GET_LIST_SUCCESS:
            return state.merge(action.condition);

        default:
            return state;
    }
};

const submitData = (state, action) => {
    switch(action.type) {
        case actions.SAVE_SUBMIT_CONDITION:
            return state.set(action.name, action.value);
        case actions.GET_RAISINGRATE_SUCCESS:
        case actions.SELECT_MODAL_DATA:
            return state.merge({...action.data});
        case actions.GET_RAISINGRATE_FAIL:
            return state.set('raisingRate', 0);
        case actions.DELETE_ALL_DETAIL:
            return state.setIn(['details'], Immutable.List());

        case actions.SELECT_DETAIL_FOR_PARTS:
            return state.updateIn(['details'], list => list.concat(Immutable.fromJS(action.data)));

        case actions.DELETE_DETAIL: {
            const index = state.get('details').findIndex(item => item.get('partId').toString() === action.id.toString());
            if(index === -1) return state;
            return state.updateIn(['details'], list => list.splice(index, 1));
        }

        case actions.UPDATE_DETAIL: {
            const {id, ...props} = action.data;
            const index = state.get('details').findIndex(item => item.get('partId').toString() === id.toString());
            if(index === -1) return state;
            return state.updateIn(['details', index], obj => obj.merge({...props}));
        }

        case actions.CLEAR_DATA:
            return Immutable.fromJS(DEFAULT_SUBMIT_DATA);

        case actions.GET_DETAIL_SUCCESS:
            return state.merge({...action.data});
        case actions.GET_INIT_SUCCESS: {
            const {enterprise = {}, isDealerUser} = action.data;
            if(!isDealerUser || state.get('dealerId'))
                return state;
            return state.merge({
                dealerId: enterprise.id,
                dealerCode: enterprise.code,
                dealerName: enterprise.name,
            });
        }
        case actions.ADD_INIT: {
            const {id, name, code} = action.data;
            return state.merge({
                dealerId: id,
                dealerCode: code,
                dealerName: name,
            });
        }
        default:
            return state;
    }
};

const domainData = combineReducers({
    initData,
    permission,
    list,
    detail
});
const appState = combineReducers({
    queryCondition,
    queryBySort,
    submitData
});
export default combineReducers({
    domainData,
    appState,
    notification
});
